package com.dailyblue.java.project.smbms.order.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dailyblue.java.commons.util.JsonResult;
import com.dailyblue.java.project.smbms.order.bean.Alipay;
import com.dailyblue.java.project.smbms.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/alipay")
@Slf4j
@CrossOrigin
public class AlipayController {
    //获取配置文件中的配置信息
    //应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    @Value("${appId}")
    private String appId;

    //商户私钥 您的PKCS8格式RSA2私钥
    @Value("${privateKey}")
    private String privateKey;

    //支付宝公钥
    @Value("${publicKey}")
    private String publicKey;

    //服务器异步通知页面路径
    @Value("${notifyUrl}")
    private String notifyUrl;

    //页面跳转同步通知页面路径
    @Value("${returnUrl}")
    private String returnUrl;

    //签名方式
    @Value("${signType}")
    private String signType;

    //字符编码格式
    @Value("${charset}")
    private String charset;

    //支付宝网关
    @Value("${gatewayUrl}")
    private String gatewayUrl;

    private final String format = "json";
    @Resource
    private OrderService orderService;

    //PC网页段支付，返回的是支付宝账号的登录页面
    @RequestMapping("/pay/{aid}/{total}/{token}")
    public String pay(@PathVariable("aid") int aid, @PathVariable("total") String total,@PathVariable("token") String token, HttpServletRequest request) throws AlipayApiException {
        log.info("aid:{},total:{}", aid, total);
        Alipay alipayBean = new Alipay();
        // 订单编号、付款金额、订单名称和订单备注
        String payId = new Date().getTime() + "." + (int) (Math.random() * 1000);
        alipayBean.setOut_trade_no(payId);
        alipayBean.setTotal_amount(total);
        alipayBean.setSubject(aid + "");
        alipayBean.setBody("没什么好说的，测试");
        // 将aid、token和payId存放到session
        request.getSession().setAttribute("AID", aid);
        request.getSession().setAttribute("payId", payId);
        request.getSession().setAttribute("token", token);
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, publicKey, signType);
        //PC网页支付使用AlipayTradePagePayRequest传参，下面调用的是pageExecute方法
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置付款成功后应跳转的路径
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);
        // 设置支付宝的参数：订单号、订单名、金额和描述
        alipayRequest.setBizContent(JSONArray.toJSONString(alipayBean));
        log.info("封装请求支付宝付款参数为:{}", JSONArray.toJSONString(alipayRequest));

        // 调用SDK生成表单
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        log.info("请求支付宝付款返回参数为:{}", result);
        return result;
    }

    @GetMapping("/success")
    public JsonResult success(HttpSession session) {
        // 1.生成订单
        // 1.1 生成订单概述
        int aid = Integer.parseInt(session.getAttribute("AID").toString());
        String payId = session.getAttribute("payId").toString();
        String token = session.getAttribute("token").toString();
        // 1.2 生成订单详情
        // 2.向rocket中发送一笔消息，更新库存
        // 3.清空购物车
        orderService.generateOrder(aid, payId, token);
        session.removeAttribute("AID");
        session.removeAttribute("payId");
        session.removeAttribute("token");
        return null;
    }
}
